
const { renderFile } = require('../lib/swig-template');
const { readYaml, write, writeJson } = require('../lib/files')
const { resolve, join } = require("path");
const { writeFileSync, existsSync, mkdirSync } = require('fs');
const { execObj } = require('../lib/tuopu.js')
const fg = require('fast-glob')


Array.prototype.last=function(){return this && this.length?this[this.length-1]:undefiend }
Array.prototype.first = function(cb){ 
    const f = this.filter(cb)
    if(f && f.length){
        return f[0]
    }
}
const configObj = readYaml("config/globe/index.yaml")


async function readConfig() {
    const config = {}
    for (let k in configObj.config) {
        const pth = configObj.config[k]
        config[k] = {}
        const files = await fg([pth])
        files.forEach(file => {
            const yamlObj = readYaml(file)
            if (yamlObj && yamlObj.name) {
                config[k][yamlObj.name] = yamlObj
                delete yamlObj.name
            }
        })
    }

    return config
}

function execNode({ execNodes, src }, context) {
    execObj(execNodes, (name, nodes) => {
        const node = nodes[name]
        if (node.src.endsWith(".yaml")) {
            const nodeConfig = readYaml(node.src)
            if (nodeConfig && nodeConfig) {
                execNode(nodeConfig, context)
            }
        }
        else if (node.src.endsWith(".js")) {
            require(resolve(__dirname, src ? "../" + src : "../", node.src))(context)
        }

    })
}

async function log() {
    const config = await readConfig()
    const context = { config }
    execNode(config.exec.execBus, context)
    if(config.globeConfig.globe.model==='dev'){
        writeJson('temp/context.yaml',context)
    }
}

log()





